<!-- 健康数据展示 -->
<template>
  <div>
    <div class="topInfoBox">
      <div class="topInfoBlock1">
        <div class="topInfoTitle">最近心率</div>
        <div class="infovalue">{{ cheartRate }}次/分钟</div>
      </div>
      <div class="topInfoBlock">
        <div class="topInfoTitle">最近血压</div>
        <div class="infovalue">
          {{ cbloodPressureLow + "/" + cbloodPressureHeight }}mmHg
        </div>
      </div>
      <div class="topInfoBlock">
        <div class="topInfoTitle">最近血糖</div>
        <div class="infovalue">{{ cbloodSugar }}%</div>
      </div>
      <div class="topInfoBlock">
        <div class="topInfoTitle">最近血氧</div>
        <div class="infovalue">{{ cspo2 }}%/分钟</div>
      </div>
      <div class="topInfoBlock">
        <div class="topInfoTitle">最近体温</div>
        <div class="infovalue">{{ cshellTemp }}℃</div>
      </div>
    </div>
    <div class="tabs" style="padding-top: 1rem">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="心率" name="heart"></el-tab-pane>
        <el-tab-pane label="血压" name="bloodpressure"></el-tab-pane>
        <el-tab-pane label="血糖" name="bloodsugar"></el-tab-pane>
        <el-tab-pane label="血氧" name="spo2"></el-tab-pane>
        <el-tab-pane label="体温" name="shelltemp"></el-tab-pane>
      </el-tabs>
    </div>
    <div
      style="
        display: flex;
        justify-content: space-between;
        padding-bottom: 1rem;
      "
    >
      <div style="display: flex">
        <div class="changeDateIcon" @click="leftClick">
          <img src="@assets/images/health/dateleft.png" />
        </div>
        <div class="datePicker">
          {{ this.startDate }}&nbsp;~&nbsp;{{ this.endDate }}
        </div>

        <div class="changeDateIcon" @click="rightClick">
          <img src="@assets/images/health/dateright.png" />
        </div>
        <!-- <el-date-picker
        disabled
          value-format="yyyy-MM-dd"
          v-model="startDate"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="endDate"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker> -->
      </div>
      <div class="dateBox">
        <el-radio-group v-model="timeInterval">
          <!-- <el-radio-button label="day">日</el-radio-button> -->
          <el-radio-button label="week">周</el-radio-button>
          <!-- <el-radio-button label="month">月</el-radio-button> -->
        </el-radio-group>
      </div>
    </div>
    <div
      id="healthEchart"
      :style="{
        width: '87rem',
        height: '30rem',
        backgroundColor: 'white',
        borderRadius: '0.5rem',
      }"
    ></div>
  </div>
</template>
<script>
import { getPhysiological, getPhysiologicalHeart } from "../../../api/index";
import { mapState } from "vuex";
export default {
  name: "healthQuery",
  computed: mapState({
    currentUserId: (state) => state.currentUserId, //当前的用户id
    loginUserInfo: (state) => state.loginUserInfo,
    userInfoDetails: (state) => state.userInfoDetails,
  }),
  data() {
    return {
      timeInterval: "week",
      activeName: "heart", //默认选中心率
      cheartRate: "--",
      cbloodPressureHeight: "--",
      cbloodPressureLow: "--",
      cbloodSugar: "--",
      cspo2: "--",
      cshellTemp: "--",
      startDate: new Date().Format("yyyy-MM-dd"),
      endDate: new Date().Format("yyyy-MM-dd"),
    };
  },
  watch: {
    timeInterval: function (newStatus, oldStatus) {
      console.log("新状态", newStatus, "旧状态", oldStatus);
      let type = this.activeName;
      this.drawEcharts(type);
    },
  },
  mounted() {
    this.getPhysiologicalData();
    this.drawEcharts("heart");
    //this.getEchartsData();
  },
  methods: {
    //点击向左切换
    leftClick(){
      let startDate = new Date(this.startDate).getTime() - 1000 * 60 * 60 * 24 * 7;
      this.startDate = new Date(startDate).Format("yyyy-MM-dd");
      let enddate = new Date(this.endDate).getTime() - 1000 * 60 * 60 * 24 * 7;
      this.endDate = new Date(enddate).Format("yyyy-MM-dd");
      let type = this.activeName;
      this.drawEcharts(type);
    },
    //点击向右切换时间
    rightClick(){
      let startDate = new Date(this.startDate).getTime() + 1000 * 60 * 60 * 24 * 7;
      this.startDate = new Date(startDate).Format("yyyy-MM-dd");
      let enddate = new Date(this.endDate).getTime() + 1000 * 60 * 60 * 24 * 7;
      this.endDate = new Date(enddate).Format("yyyy-MM-dd");
      let type = this.activeName;
      this.drawEcharts(type);
    },
    //点击切换生理类型
    handleClick(tab) {
      let type = tab.name;
      this.drawEcharts(type);
    },
    //获取echarts图表所需数据
    async getEchartsData(type) {
      console.log("选中的时间间隔", this.timeInterval);
      if (this.timeInterval == "day") {
        this.startDate = this.endDate;
      } else if (this.timeInterval == "week") {
        let data1 = new Date(this.endDate).getTime() - 1000 * 60 * 60 * 24 * 7;
        this.startDate = new Date(data1).Format("yyyy-MM-dd");
      } else if (this.timeInterval == "month") {
        let data1 = new Date(this.endDate).getTime() - 1000 * 60 * 60 * 24 * 30;
        this.startDate = new Date(data1).Format("yyyy-MM-dd");
      }
      console.log("开始时间", this.startDate, this.endDate);
      let data = {
        resid: this.currentUserId,
        date1: this.startDate,
        date2: this.endDate,
        type: type,
      };
      const res = await getPhysiologicalHeart(JSON.stringify(data));
      if (res.code == 0) {
        return res.records;
      } else {
        return [
          {
            time: this.endDate,
            value: "0",
            value1: "0",
          },
        ];
      }
    },
    //获取最近生理数据
    async getPhysiologicalData() {
      await getPhysiological(this.currentUserId)
        .then((res) => {
          let data = res;
          if (data.code == 0) {
            let records = data.records;
            this.cheartRate =
              records.heartRate.length > 1
                ? records.heartRate[records.heartRate.length - 1].value
                : "--";
            this.cbloodPressureHeight =
              records.bloodPressure.length > 1
                ? records.bloodPressure[records.bloodPressure.length - 1].value1
                : "--";
            this.cbloodPressureLow =
              records.bloodPressure.length > 1
                ? records.bloodPressure[records.bloodPressure.length - 1].value
                : "--";
            this.cbloodSugar =
              records.bloodSugar.length > 1
                ? records.bloodSugar[records.bloodSugar.length - 1].value
                : "--";
            this.cspo2 =
              records.spo2.length > 1
                ? records.spo2[records.spo2.length - 1].value
                : "--";
            this.cshellTemp =
              records.shellTemp.length > 1
                ? records.shellTemp[records.shellTemp.length - 1].value
                : "--";
          } else {
            this.$message.error("获取生理数据失败");
          }
        })
        .catch((error) => {
          console.log("失败", error);
          this.$message.error("获取生理数据失败");
        });
    },
    drawEcharts(type) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("healthEchart"));
      myChart.setOption({});
      this.getEchartsData(type).then((res) => {
        let alldata = res;
        let datax = [];
        let datay = [];
        let datay1 = [];
        let series = [];
        let legend = [];
        let yname = "";
        let interval = 1;
        if (alldata && alldata.length > 0) {
          interval = Math.floor(alldata.length / 8);
        }
        if (type != "bloodpressure") {
          series = [];
          alldata.map((item) => {
            datax.push(item.time.substring(5, 16));
            datay.push(item.value);
          });
          let name = "";
          if (type == "heart") {
            name = "心率";
            yname = "次/分钟";
          } else if (type == "bloodsugar") {
            name = "血糖";
            yname = "%";
          } else if (type == "spo2") {
            name = "血氧";
            yname = "%/分钟";
          } else if (type == "shelltemp") {
            name = "体温";
            yname = "℃";
          }
          legend.push(name); //图例
          series.push({
            name: name,
            type: "line",
            color: "#5FD990",
            data: datay,
          });
        } else {
          yname = "mmHg";
          series = [];
          alldata.map((item) => {
            datax.push(item.time.substring(5, 16));
            datay.push(item.value);
            datay1.push(item.value1); //高压
          });
          legend.push("收缩压", "舒张压");
          series.push(
            {
              name: "收缩压",
              type: "line",
              color: "#5FD990",
              data: datay1,
            },
            {
              name: "舒张压",
              type: "line",
              color: "orange",
              data: datay,
            }
          );
        }
        // 绘制图表
        myChart.setOption(
          {
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "shadow",
                label: {
                  show: true,
                },
              },
              textStyle: {
                fontSize: 16,
              },
              confine: true,
            },
            legend: {
              data: legend,
              top: "8%",
              right: "5%",
              textStyle: {
                fontSize: 16, // 文字的字体大小。
              },
            },
            grid: {
              top: "20%",
              bottom: "30%", //也可设置left和right设置距离来控制图表的大小
            },
            xAxis: {
              type: "category",
              data: datax,
              name: "时间",
              axisTick: {
                show: true, //隐藏X轴刻度
              },
              axisLabel: {
                rotate: 42,
                interval: interval,
                color: "#666",
                fontSize: 16,
              },
              nameTextStyle: {
                fontSize: 16,
              },
            },
            yAxis: [
              {
                type: "value",
                name: yname,
                nameTextStyle: {
                  //坐标轴名称的字体样式
                  fontSize: 16,
                  padding: 10,
                },
                splitLine: {
                  lineStyle: {
                    type: "dashed",
                  },
                },
                axisLabel: {
                  fontSize: 16,
                },
              },
            ],
            series: series,
          },
          true
        );
      });
      //多图表自适应
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },
  },
};
</script>
<style scoped>
/* 最近生理数据 */
.topInfoBox {
  display: flex;
  padding: 0.5rem 0rem 0rem;
}
.topInfoBlock1 {
  text-align: left;
  line-height: 1.9rem;
}
.topInfoBlock {
  margin-left: 2rem;
  text-align: left;
  line-height: 1.9rem;
}
.infovalue {
  color: #5fd990;
}
.topInfoTitle {
  font-weight: bold;
}
.dateBox {
  margin-right: 0rem;
}
.datePicker {
  font-size: 1rem;
  line-height: 2rem;
  margin: 0 0.5rem;
}
.tabs .el-tabs /deep/ .el-tabs__item {
  font-size: 0.95rem !important;
}
.changeDateIcon {
  width: 2rem;
  height: 2rem;
  cursor: pointer;
}
.changeDateIcon img {
  width: 2rem;
  height: 2rem;
}
</style>
